package com.hdaccp.hadoop.mr3;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class NumApp {
    public static class NumMapper extends Mapper<LongWritable,Text,LongWritable,Text>
    {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            long line = Long.parseLong(value.toString()) ;
            context.write(new LongWritable(line),new Text(""));
        }
    }

    public static class NumReducer extends Reducer<LongWritable,Text,LongWritable,Text>
    {
        @Override
        protected void reduce(LongWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
           context.write(key,new Text(""));
        }
    }

    public static void main(String[] args) throws  Exception{
        if(args.length<=0){
            System.err.print("请配置参数");
            System.exit(1);
        }


        //1.读取配置文件
        Configuration cfg = new Configuration() ;
        //2.产生作业
        Job job = Job.getInstance(cfg,"mr3.job1") ;
        //3.配置作业
        job.setJarByClass(NumApp.class);
        //4.1.配置作业 之 mapper
        job.setMapperClass(NumMapper.class);
        job.setMapOutputKeyClass(LongWritable.class);
        job.setMapOutputValueClass(Text.class);
        //4.2配置作业 之 mapper 目标文件
        FileInputFormat.setInputPaths(job,new Path(args[0]));

        //5.1.配置作业 之 reducer
        job.setReducerClass(NumReducer.class);
        job.setOutputKeyClass(LongWritable.class);
        job.setOutputValueClass(Text.class);
        Path pathout = new Path(args[1]) ;
        //得到hdfs的文件系统
        //   FileSystem fileSystem = FileSystem.get(new URI(cfg.get("fs.defaultFS")),cfg,"root") ;

        FileSystem fileSystem = FileSystem.get(cfg) ;

        if(fileSystem.exists(pathout)){
            fileSystem.delete(pathout,true) ;
        }




        job.setNumReduceTasks(1);
        FileOutputFormat.setOutputPath(job,pathout);



        //6 提交作业

        System.exit(job.waitForCompletion(true)?0:1) ;
    }
}
